package com.lan.controller.sys;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lan.SysConstants;
import com.lan.controller.BaseController;
import com.lan.entity.sys.Menu;
import com.lan.entity.sys.Role;
import com.lan.service.sys.MenuService;
import com.lan.service.sys.RoleService;
import com.lan.utils.tree.TreeNode;
import com.lan.viewObject.Result;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  role Controller
 * </p>
 *
 * @author shadow
 * @since 2022-06-04
 */
@Controller
@RequestMapping("/role")
@RequiresPermissions("role:list")
public class RoleController extends BaseController {

    @Resource
    private RoleService roleService;
    @Resource
    private MenuService menuService;

    /**
     * 列表 页.
     *
     * */
    @GetMapping("/list")
    public String list() {
        return "sys/role/list";
    }

    /**
     * 新增 页.
     *
     * */
    @GetMapping("/add")
    public String add(final ModelMap model) {
        model.addAttribute(SysConstants.ROLE, new Role());
        return "sys/role/add";
    }

    /**
     * 编辑 页.
     *
     * */
    @GetMapping("/edit/{id}")
    public String edit(final ModelMap model, @PathVariable("id") final String id) {
        Role role = roleService.getById(id);
        if (null == role)
            role = new Role();
        model.addAttribute(SysConstants.ROLE, role);
        return "sys/role/edit";
    }

    /**
     * 配置 页.
     *
     * */
    @GetMapping("/config/{id}")
    public String config(final ModelMap model, @PathVariable("id") final String id) {
        List<TreeNode<Menu>> menuTree = menuService.getMenuTree(id);
        model.addAttribute("data", menuTree);
        model.addAttribute("id", id);
        return "sys/role/config";
    }

    /**
     * 列表.
     *
     * */
    @ResponseBody
    @PostMapping("/list")
    public Result getList(final Role role) {
        List<Role> list = roleService.getListByWrapper(role);
        return Result.ok()
                .put(Result.CODE, 0)
                .put(Result.STATUS, 200)
                .put(Result.DATA, list)
                .put(Result.COUNT, list.size())
                .put(Result.MSG, "");
    }

    /**
     * 保存 || 更新.
     *
     * */
    @ResponseBody
    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(final Role role) {
        try {
            Role newEntity = new Role();
            String id = role.getId();
            //编辑
            if (null != id && id.length() > 0) {
                newEntity = roleService.getById(id);
                if (null == newEntity)
                    return Result.error(0, "角色不存在");
                Role u = roleService.getRoleByCode(role.getCode());
                if (null != u && (!id.equals(u.getId())))
                    return Result.error(0, "角色已存在");
                newEntity.setCode(role.getCode())
                        .setName(role.getName())
                        .setIntroduction(role.getIntroduction())
                        .setUpdated(LocalDateTime.now());
            } else { //新增
                if (null != roleService.getRoleByCode(role.getCode()))
                    return Result.error("角色已存在");
                BeanUtils.copyProperties(role, newEntity);
                newEntity.setId(UUID.randomUUID().toString())
                        .setStatus("1")
                        .setCreated(LocalDateTime.now())
                        .setUpdated(LocalDateTime.now());
            }
            if (!isFullField(newEntity))
                return Result.error("字段不全");
            roleService.saveOrUpdate(newEntity);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return Result.ok();
    }

    /**
     * 删除.
     *
     * */
    @ResponseBody
    @PostMapping("/del/{id}")
    public Result del(@PathVariable("id") final String id) {
        Role role = roleService.getById(id);
        if (null == role)
            return Result.error(0, "角色不存在");
        role.setStatus("0");
        UpdateWrapper<Role> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status", "0");
        updateWrapper.eq("id", id);
        roleService.update(updateWrapper);
        return Result.ok();
    }

    /**
     * 配置.
     *
     * */
    @ResponseBody
    @PostMapping("/config/{id}/{menuArr}")
    public Result config(@PathVariable("id") final String id, @PathVariable("menuArr") String menuArr) {
        roleService.config(id, menuArr);
        return Result.ok();
    }

}
